import logging
from blls.base_bll import BaseBLL
from models.user_models.system_user_model import SystemUsers
from utils.common_util import CommonUtil
from utils.guid_util import GUIDUtil
from dtos.result import Result
from config import APP
from utils.token_util import Token
from enumobjects.general_enum import YesOrNoEnum


class UserBLL(BaseBLL):

    def create_or_update_user(self, ldap_info):
        user_check = self.db_session.query(SystemUsers).filter(
            SystemUsers.username == ldap_info['username'],
            SystemUsers.is_delete == 0
        ).first()
        self.db_session.begin(subtransactions=True)
        try:
            if not user_check:
                user_check = SystemUsers(
                    guid=str(GUIDUtil.generate()),
                    name=ldap_info['name'],
                    username=ldap_info['username'],
                    mail=ldap_info['mail'],
                    phone=ldap_info['mobile'],
                    last_login_time=CommonUtil.get_timestamp()
                )
                self.db_session.add(user_check)
                logging.info("创建了一个用户：%s" % ldap_info['username'])
            else:
                user_check.name = ldap_info['name']
                user_check.mail = ldap_info['mail']
                user_check.phone = ldap_info['mobile']
                user_check.last_login_time = CommonUtil.get_timestamp()
                logging.info("更新了一个用户：%s" % ldap_info['username'])
            self.db_session.commit()
            return user_check
        except Exception as ex:
            self.db_session.rollback()
            logging.info("创建或新增用户时出现异常，原因：%s" % str(ex))
            return None

    def verify(self):
        userinfo = self.request.get_current_userinfo()
        user_obj = self.db_session.query(SystemUsers).filter_by(username=userinfo['username']).first()
        if user_obj is not None:
            role = user_obj.role
        else:
            role = 0
        if not userinfo:
            return None
        project_list = userinfo.get("project_list", [])
        app = userinfo.get("app")
        if str(app) != APP:
            return None
        if str(app) not in project_list:
            return None
        user_obj = self.create_or_update_user(userinfo)
        if not user_obj:
            return None
        data = Token().get_token(**userinfo)
        data['username'] = userinfo['username']
        data['name'] = userinfo['name']
        data['mail'] = userinfo['mail']
        data['mobile'] = userinfo['mobile']
        data['role'] = role
        return data

    def login(self):
        user_check = self.verify()
        if not user_check:
            return Result.error_result(message="错误的账号或密码")
        return Result.success_result(data=user_check)

    def refresh_token(self):
        userinfo = self.request.get_current_userinfo()
        if not userinfo:
            return Result.error_result(message="原token完全过期")
        return Result.success_result(data=Token().get_token(**userinfo))

    def edit_user_role(self, guid, role):
        if role not in [1, 2]:
            return Result.error_result(message="没有此角色")
        user_obj = self.db_session.query(SystemUsers).filter(
            SystemUsers.is_delete == YesOrNoEnum.NO.value,
            SystemUsers.guid == guid
        ).first()
        if not user_obj:
            return Result.error_result(message="未找到该用户")
        self.db_session.begin(subtransactions=True)
        try:
            user_obj.role = role
            user_obj.last_update_time = CommonUtil.get_timestamp()
            self.db_session.commit()
            return Result.success_result(message="修改用户角色成功")
        except Exception as ex:
            message = "修改用户角色错误，原因是：%s" % str(ex)
            logging.info(message)
            return Result.error_result(message=message)